package com.c2b.algorithm.leetcode.base;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <a href='https://leetcode.cn/problems/find-common-characters/'>查找共用字符(Find Common Characters)</a>
 * <p>给你一个字符串数组 words ，请你找出所有在 words 的每个字符串中都出现的共用字符（ 包括重复字符），并以数组形式返回。你可以按 任意顺序 返回答案。 </p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：words = ["bella","label","roller"]
 *      输出：["e","l","l"]
 *
 * 示例 2：
 *      输入：words = ["cool","lock","cook"]
 *      输出：["c","o"]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= words.length <= 100</li>
 *         <li>1 <= words[i].length <= 100</li>
 *         <li>words[i] 由小写英文字母组成</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/12/19 15:34
 */
public class LC1002FindCommonCharacters_S {

    static class Solution {
        public List<String> commonChars(String[] words) {
            int[] minFreq = new int[26];
            Arrays.fill(minFreq, Integer.MAX_VALUE);
            for (String word : words) {
                int[] currFreq = new int[26];
                for (char ch : word.toCharArray()) {
                    ++currFreq[ch - 'a'];
                }
                for (int j = 0; j < 26; j++) {
                    minFreq[j] = Math.min(minFreq[j], currFreq[j]);
                }
            }
            List<String> resList = new ArrayList<>();
            for (int i = 0; i < minFreq.length; i++) {
                for (int i1 = 0; i1 < minFreq[i]; i1++) {
                    resList.add(String.valueOf((char) (i + 'a')));
                }
            }
            return resList;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.commonChars(new String[]{"bella", "label", "roller"}));
        System.out.println(solution.commonChars(new String[]{"cool", "lock", "cook"}));
    }
}
